<template>
  <el-card class="content-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>API文档 - 基础示例</span>
      </div>
    </template>

    <div class="content-container">
      <div class="api-content">
        <div class="section" id="intro">
          <div class="section-header"><h2>基础示例介绍</h2></div>
          <p class="intro-text">
            本页面提供了API的基础使用示例，帮助您快速了解如何在项目中集成和使用我们的API服务。
            这些示例涵盖了最常见的使用场景，适合初次接触我们API的开发者。
          </p>
        </div>

        <div class="section" id="authentication">
          <div class="section-header"><h2>认证示例</h2></div>
          <p>在使用API之前，您需要进行身份认证。以下是一个基本的认证示例：</p>
          <div class="code-block">
            <div class="code-header">
              <span>JavaScript</span>
              <el-button
                type="primary"
                size="small"
                :icon="CopyDocument"
                @click="copyCode(authCode)"
                class="copy-btn"
              >
                复制代码
              </el-button>
            </div>
            <MonacoEditor
              style="height: 180px; border-radius: 6px; overflow: hidden"
              v-model="authCode"
              language="javascript"
              :options="{
                readOnly: true,
                minimap: { enabled: false },
                height: '180px',
              }"
            />
          </div>
        </div>

        <div class="section" id="data-fetch">
          <div class="section-header"><h2>数据获取示例</h2></div>
          <p>以下示例展示了如何获取基本数据：</p>
          <div class="code-block">
            <div class="code-header">
              <span>JavaScript</span>
              <el-button
                type="primary"
                size="small"
                :icon="CopyDocument"
                @click="copyCode(fetchCode)"
                class="copy-btn"
              >
                复制代码
              </el-button>
            </div>
            <MonacoEditor
              style="height: 200px; border-radius: 6px; overflow: hidden"
              v-model="fetchCode"
              language="javascript"
              :options="{
                readOnly: true,
                minimap: { enabled: false },
                height: '200px',
              }"
            />
          </div>
        </div>

        <div class="section" id="data-submit">
          <div class="section-header"><h2>数据提交示例</h2></div>
          <p>以下示例展示了如何提交数据：</p>
          <div class="code-block">
            <div class="code-header">
              <span>JavaScript</span>
              <el-button
                type="primary"
                size="small"
                :icon="CopyDocument"
                @click="copyCode(submitCode)"
                class="copy-btn"
              >
                复制代码
              </el-button>
            </div>
            <MonacoEditor
              style="height: 200px; border-radius: 6px; overflow: hidden"
              v-model="submitCode"
              language="javascript"
              :options="{
                readOnly: true,
                minimap: { enabled: false },
                height: '200px',
              }"
            />
          </div>
        </div>

        <div class="section" id="error-handling">
          <div class="section-header"><h2>错误处理示例</h2></div>
          <p>良好的错误处理对于构建健壮的应用至关重要。以下是一个基本的错误处理示例：</p>
          <div class="code-block">
            <div class="code-header">
              <span>JavaScript</span>
              <el-button
                type="primary"
                size="small"
                :icon="CopyDocument"
                @click="copyCode(errorCode)"
                class="copy-btn"
              >
                复制代码
              </el-button>
            </div>
            <MonacoEditor
              style="height: 200px; border-radius: 6px; overflow: hidden"
              v-model="errorCode"
              language="javascript"
              :options="{
                readOnly: true,
                minimap: { enabled: false },
                height: '200px',
              }"
            />
          </div>
        </div>
      </div>

      <!-- 右侧悬浮目录 -->
      <div class="toc">
        <div class="toc-title">目录</div>
        <div class="toc-item" @click="scrollToSection('intro')">
          基础示例介绍
        </div>
        <div class="toc-item" @click="scrollToSection('authentication')">
          认证示例
        </div>
        <div class="toc-item" @click="scrollToSection('data-fetch')">
          数据获取示例
        </div>
        <div class="toc-item" @click="scrollToSection('data-submit')">
          数据提交示例
        </div>
        <div class="toc-item" @click="scrollToSection('error-handling')">
          错误处理示例
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref } from 'vue';
import { CopyDocument } from '@element-plus/icons-vue';
import MonacoEditor from '@/components/MonacoEditor.vue';

// 示例代码
const authCode = ref(`// 引入SDK
import { initializeApi } from 'api-client';

// 初始化API客户端
const apiClient = initializeApi({
  apiKey: 'YOUR_API_KEY',
  environment: 'production', // 或 'development'
  timeout: 30000 // 超时时间，单位毫秒
});

// 验证连接
apiClient.verifyConnection()
  .then(response => {
    console.log('认证成功:', response);
  })
  .catch(error => {
    console.error('认证失败:', error);
  });`);

const fetchCode = ref(`// 获取数据列表
async function fetchDataList() {
  try {
    const params = {
      page: 1,
      pageSize: 10,
      sortBy: 'createdAt',
      order: 'desc'
    };
    
    const response = await apiClient.data.getList(params);
    console.log('获取数据成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('获取数据失败:', error);
    throw error;
  }
}

// 获取单个数据详情
async function fetchDataDetail(id) {
  try {
    const response = await apiClient.data.getDetail({ id });
    console.log('获取详情成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('获取详情失败:', error);
    throw error;
  }
}`);

const submitCode = ref(`// 创建新数据
async function createData(data) {
  try {
    const payload = {
      title: data.title,
      content: data.content,
      tags: data.tags || [],
      isPublic: data.isPublic || false
    };
    
    const response = await apiClient.data.create(payload);
    console.log('创建成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('创建失败:', error);
    throw error;
  }
}

// 更新数据
async function updateData(id, data) {
  try {
    const payload = {
      id,
      ...data
    };
    
    const response = await apiClient.data.update(payload);
    console.log('更新成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('更新失败:', error);
    throw error;
  }
}`);

const errorCode = ref(`// 全局错误处理
apiClient.setErrorHandler((error) => {
  if (error.response) {
    // 服务器返回错误响应
    const status = error.response.status;
    const data = error.response.data;
    
    switch (status) {
      case 400:
        console.error('请求参数错误:', data.message);
        break;
      case 401:
        console.error('认证失败，请重新登录');
        // 跳转到登录页或刷新token
        break;
      case 403:
        console.error('没有权限访问该资源');
        break;
      case 404:
        console.error('请求的资源不存在');
        break;
      case 500:
        console.error('服务器内部错误');
        break;
      default:
        console.error('请求失败:', data.message || '未知错误');
    }
  } else if (error.request) {
    // 请求发送但没有收到响应
    console.error('网络错误，请检查您的网络连接');
  } else {
    // 请求配置错误
    console.error('请求配置错误:', error.message);
  }
  
  return Promise.reject(error);
});`);

// 复制代码功能
const copyCode = (code) => {
  navigator.clipboard.writeText(code.value)
    .then(() => {
      ElMessage.success('代码已复制到剪贴板');
    })
    .catch(() => {
      ElMessage.error('复制失败');
    });
};

// 滚动到指定区域
const scrollToSection = (sectionId) => {
  const element = document.getElementById(sectionId);
  if (element) {
    element.scrollIntoView({ behavior: "smooth" });
  }
};
</script>

<style scoped>
.content-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.card-header {
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

:deep(.el-card__body) {
  padding: 0;
  height: calc(100% - 60px);
  overflow-y: auto;
  background: #ffffff;
}

.content-container {
  min-height: 100%;
  padding: 30px;
  padding-right: 280px;
  background: linear-gradient(to bottom, #ffffff 0%, #f8f9fa 100%);
}

.api-content {
  max-width: 1000px;
  margin: 0 auto;
  line-height: 1.8;
  color: #4a5568;
}

.section {
  margin-bottom: 40px;
  padding: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section h2 {
  margin: 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
  position: relative;
  flex: 1;
}

.section h2::before {
  content: "";
  position: absolute;
  left: 0;
  bottom: -2px;
  width: 50px;
  height: 2px;
  background: #409eff;
  border-radius: 1px;
}

.intro-text {
  font-size: 16px;
  line-height: 1.8;
  color: #4a5568;
  margin-bottom: 20px;
}

.code-block {
  margin: 15px 0;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
}

.copy-btn {
  margin-left: 10px;
}

/* 右侧悬浮目录样式 */
.toc {
  position: fixed;
  right: 50px;
  top: 50%;
  transform: translateY(-50%);
  background: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  border: 1px solid #e4e7ed;
  min-width: 200px;
}

.toc-title {
  font-weight: 700;
  margin-bottom: 15px;
  color: #2d3748;
  font-size: 18px;
  text-align: center;
  padding-bottom: 10px;
  border-bottom: 2px solid #e2e8f0;
}

.toc-item {
  padding: 12px 16px;
  cursor: pointer;
  color: #4a5568;
  transition: all 0.3s ease;
  border-radius: 8px;
  font-size: 14px;
  margin-bottom: 4px;
  border-left: 3px solid transparent;
  position: relative;
}

.toc-item:hover {
  color: #409eff;
  background: #ecf5ff;
  border-left-color: #409eff;
  transform: translateX(4px);
}

.toc-item:active {
  transform: translateX(2px);
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .content-container {
    padding-right: 30px;
  }

  .toc {
    display: none;
  }
}

@media (max-width: 768px) {
  .content-container {
    padding: 20px 15px;
  }

  .section {
    padding: 20px 15px;
    margin-bottom: 25px;
  }

  .section h2 {
    font-size: 18px;
  }

  .card-header {
    font-size: 16px;
    padding: 15px;
  }
}

/* 滚动条样式 */
:deep(.el-card__body)::-webkit-scrollbar {
  width: 6px;
}

:deep(.el-card__body)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

:deep(.el-card__body)::-webkit-scrollbar-thumb {
  background: #409eff;
  border-radius: 3px;
}

:deep(.el-card__body)::-webkit-scrollbar-thumb:hover {
  background: #337ecc;
}
</style>